from fastapi import APIRouter, Depends, HTTPException
from .factory_sovits_schema import ChatSchema
from utils.save_chat import save_chat_to_json
from starlette.responses import JSONResponse
from utils.dependent import restricted_ip
from fastapi import BackgroundTasks
from .llama_factory import chat
from fastapi import Depends
from .gpt_sovits import tts
import asyncio

# 创建API路由实例
router = APIRouter(
    prefix="/",
    tags=["factory_sovits"],
    responses={404: {"description": "Not found"}},
)
# 定义全局异步锁，用于控制并发请求
lock = asyncio.Lock()


@router.post("/chat")
async def chats(chat_info: ChatSchema, background_tasks: BackgroundTasks, r_ip: dict = Depends(restricted_ip)):
    if r_ip is False:
        return JSONResponse(status_code=200,
                            content={"code": 200, "success": True, "data": {
                                "msg": "失败",
                                "content": "权限不足",
                                "audioUrl": f"https://api.ghy-web.com/static/audio/权限不足.wav"}
                                     }
                            )
    # chat_text = chat(chat_info)
    chat_text = chat(chat_info)
    new_chat = {
        "prompt": chat_info.content,
        "response": chat_text,
        "history": []
    }
    background_tasks.add_task(save_chat_to_json, new_chat=new_chat, file_name="./chats.json")

    audio_path = await tts(chat_text)
    return JSONResponse(status_code=200,
                        content={"code": 200, "success": True, "data": {
                            "msg": "成功",
                            "content": chat_text,
                            "audioUrl": f"https://api.ghy-web.com/{audio_path}"
                        }})


@router.post("/clear_history")
async def clear_history(r_ip: dict = Depends(restricted_ip)):
    if r_ip is False:
        return JSONResponse(status_code=200,
                            content={"code": 200, "success": True, "data": {
                                "msg": "失败",
                                "content": "权限不足",
                                "audioUrl": f"https://api.ghy-web.com/static/audio/权限不足.wav"
                            }})
    chat({
        "role": "user",
        "content": "请忘记我们之间的所有对话，清空所有记录，让我们开始新的对话"
    })
    return JSONResponse(status_code=200,
                        content={"code": 200, "success": True, "msg": "清空成功"})
